﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System.IO
Imports Boogaloo.Core.UI
Imports Boogaloo.Admin.UI.Controls
Imports Boogaloo.Core
Imports Boogaloo.Core.BLL


Namespace UI.Webpages


    Partial Public Class TagsGroups
        Inherits BaseAdminPage

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            If Not Page.IsPostBack Then
                ClearTagMovers()
                BindPage()
            End If

        End Sub


        Private Sub BindPage()

            ' Bundles
            Dim bundles As New List(Of TagBundle)
            bundles.Add(New TagBundle(0, Groove.admin_root.root_id, "Unbundled tags", Nothing, Nothing, Nothing))
            Dim user_bundles As List(Of TagBundle) = TagBundle.GetTagBundles(Groove.admin_root.root_id)
            enable_mover = user_bundles.Count > 0

            bundles.AddRange(user_bundles)

            rpt_bundles.DataSource = bundles
            rpt_bundles.DataBind()

            ' movers
            rpt_movers.DataSource = GetTagMovers() ' list stored in session
            rpt_movers.DataBind()

            If enable_mover And rpt_movers.Items.Count > 0 Then
                pnl_movers.Visible = True
                ddl_movebundle.DataSource = user_bundles
                ddl_movebundle.DataTextField = "name"
                ddl_movebundle.DataValueField = "bundle_id"
                ddl_movebundle.DataBind()
                ddl_movebundle.Items.Insert(0, New ListItem("Unbundled tags", 0))
                ddl_movebundle.Items.Insert(0, New ListItem("Select destination bundle", "-1"))
            Else
                pnl_movers.Visible = False
            End If

            ' Groups
            rpt_groups.DataSource = Group.GetGroups(Groove.admin_root.root_id)
            rpt_groups.DataBind()
            If rpt_groups.Items.Count = 0 Then
                lbl_nogroups.Visible = True
            Else
                lbl_nogroups.Visible = False
            End If


        End Sub


#Region "Tags"




        Protected Sub rpt_bundles_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_bundles.ItemDataBound

            Dim tb As TagBundle = CType(e.Item.DataItem, TagBundle)
            If tb IsNot Nothing Then
                Dim dwiz As CommitWizard = CType(e.Item.FindControl("dwiz_bundle"), CommitWizard)

                CType(e.Item.FindControl("lit_name"), Literal).Text = tb.name

                Dim rpt As Repeater = CType(e.Item.FindControl("rpt_tag"), Repeater)
                If tb.bundle_id = 0 Then
                    ' this is the special case "unbundled tags"
                    rpt.DataSource = Tag.GetBundableTags(Groove.admin_root.root_id)
                    dwiz.Visible = False
                Else
                    rpt.DataSource = Tag.GetBundledTags(tb.bundle_id)
                    dwiz.CommandArgument = tb.bundle_id
                End If
                rpt.DataBind()

            End If

        End Sub

        Protected Sub rpt_tag_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)

            Dim t As Tag = CType(e.Item.DataItem, Tag)
            If t IsNot Nothing Then
                Dim lb As LinkButton = CType(e.Item.FindControl("lb"), LinkButton)
                lb.Attributes.Add("rel", "tag")
                lb.CommandArgument = t.tag_id
                lb.Text = t.name


                If Not enable_mover Or TagMoversContains(t) Then
                    lb.Enabled = False
                Else
                    lb.Enabled = True
                End If

                Select Case True
                    Case t.count <= tag_standeviation * 2 And t.count > tag_standeviation
                        lb.CssClass = "small"
                    Case t.count <= tag_standeviation * 3 And t.count > tag_standeviation * 2
                        lb.CssClass = "big"
                    Case t.count <= tag_standeviation * 4 And t.count > tag_standeviation * 3
                        lb.CssClass = "bigger"
                    Case t.count > tag_standeviation * 4
                        lb.CssClass = "biggest"
                    Case Else
                        lb.CssClass = "smallest"
                End Select
            End If

        End Sub



        Protected Sub dwiz_bundle_Click(ByVal sender As Object, ByVal e As EventArgs)

            Dim dwiz As CommitWizard = CType(sender, CommitWizard)
            If dwiz IsNot Nothing Then
                TagBundle.DeleteTagBundle(CType(dwiz.CommandArgument, Integer))
            End If
            BindPage()
        End Sub


        Protected Sub lb_save_bundle_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_save_bundle.Click
            If Page.IsValid Then
                TagBundle.InsertTagBundle(Groove.admin_root.root_id, txt_bundle.Text)
                txt_bundle.Text = String.Empty
                BindPage()
            End If
        End Sub


#End Region

#Region "TagMovers"

        Protected Sub rpt_movers_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_movers.ItemDataBound
            Dim t As Tag = CType(e.Item.DataItem, Tag)
            If t IsNot Nothing Then
                CType(e.Item.FindControl("lit"), Literal).Text = t.name
            End If
        End Sub


        Protected Sub ddl_movebundle_SelectedIndexChanges(ByVal sender As Object, ByVal e As EventArgs) Handles ddl_movebundle.SelectedIndexChanged
            Dim t As Tag = Nothing
            Dim movers As List(Of Tag) = GetTagMovers()
            Dim bundle_id As Integer = CType(ddl_movebundle.SelectedValue, Integer)
            If bundle_id >= 0 Then
                For Each t In movers
                    t.bundle_id = bundle_id
                    t.Update()
                Next
            End If
            ClearTagMovers()
            BindPage()
        End Sub


        Protected Sub lb_clearmovers_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_clearmovers.Click
            ClearTagMovers()
            BindPage()
        End Sub

        Private Function TagMoversContains(ByVal t As Tag) As Boolean
            Dim movers As List(Of Tag) = GetTagMovers()
            Dim found As Boolean = False
            Dim mt As Tag = Nothing
            For Each mt In movers
                If mt.tag_id = t.tag_id Then
                    found = True
                    Exit For
                End If
            Next
            Return found
        End Function

        Private Function GetTagMovers() As List(Of Tag)
            If Session(session_movers_key) IsNot Nothing Then
                Return CType(Session(session_movers_key), List(Of Tag))
            Else
                Return New List(Of Tag)
            End If
        End Function

        Private Sub SaveTagMovers(ByVal tags As List(Of Tag))
            Session(session_movers_key) = tags
        End Sub

        Private Sub ClearTagMovers()
            Session(session_movers_key) = Nothing
        End Sub

        Protected Sub lb_addtomover_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim lb As LinkButton = CType(sender, LinkButton)
            If lb IsNot Nothing Then
                Dim t As Tag = Tag.GetTag(CType(lb.CommandArgument, Integer))
                If t IsNot Nothing Then
                    If Not TagMoversContains(t) Then
                        Dim movers As List(Of Tag) = GetTagMovers()
                        movers.Add(t)
                        SaveTagMovers(movers)
                    End If
                End If
            End If
            BindPage()
        End Sub

#End Region

#Region "Groups"

        Protected Sub rpt_groups_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_groups.ItemDataBound

            Dim g As Group = CType(e.Item.DataItem, Group)
            If g IsNot Nothing Then

                CType(e.Item.FindControl("lbl_txt_group_name"), Label).Text = g.name
                CType(e.Item.FindControl("txt_group_name"), TextBox).Text = g.name
                CType(e.Item.FindControl("rfv_txt_group_name"), RequiredFieldValidator).ValidationGroup = "groupname" & g.group_id.ToString
                CType(e.Item.FindControl("lbl_txt_group_description"), Label).Text = g.description
                CType(e.Item.FindControl("txt_group_description"), TextBox).Text = g.description
                CType(e.Item.FindControl("hyp_cancel"), HyperLink).NavigateUrl = Request.Url.PathAndQuery
                Dim lb_save As LinkButton = CType(e.Item.FindControl("lb_save"), LinkButton)
                Dim dwiz As CommitWizard = CType(e.Item.FindControl("dwiz_group"), CommitWizard)
                lb_save.CommandName = "savegroup"
                lb_save.CommandArgument = String.Format("{0}|{1}", e.Item.ItemIndex, g.group_id)
                lb_save.ValidationGroup = "groupname" & g.group_id.ToString
                dwiz.CommandArgument = g.group_id
            End If

        End Sub

        ''' <summary>
        ''' Creates a new group associated with this this root
        ''' </summary>
        Protected Sub lb_group_add_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_group_add.Click
            If Page.IsValid Then
                Group.InsertGroup(Groove.admin_root.root_id, txt_group_name.Text, txt_group_description.Text)
                txt_group_name.Text = String.Empty
                txt_group_description.Text = String.Empty
            End If
            BindPage()
        End Sub

        Protected Sub lb_group_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim lb As LinkButton = CType(sender, LinkButton)
            If lb IsNot Nothing Then
                Dim args() As String = lb.CommandArgument.Split("|")
                If args.Length Then
                    Dim ri As RepeaterItem = rpt_groups.Items(CType(args(0), Integer))
                    Dim group_id As Integer = CType(args(1), Integer)
                    If lb.CommandName.ToLower = "savegroup" Then
                        Dim name As String = CType(ri.FindControl("txt_group_name"), TextBox).Text
                        Dim desc As String = CType(ri.FindControl("txt_group_description"), TextBox).Text
                        Group.UpdateGroup(group_id, Groove.admin_root.root_id, name, desc)
                    End If
                End If
            End If
            BindPage()
        End Sub

        Protected Sub dwiz_group_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim dwiz As CommitWizard = CType(sender, CommitWizard)
            If dwiz IsNot Nothing Then
                Dim group_id As Integer = CType(dwiz.CommandArgument, Integer)
                Group.DeleteGroup(group_id)
            End If
            BindPage()
        End Sub


#End Region


#Region "Properties"

        Private _enable_mover As Boolean = False
        Public Property enable_mover() As Boolean
            Get
                Return _enable_mover
            End Get
            Set(ByVal value As Boolean)
                _enable_mover = value
            End Set
        End Property



        Private ReadOnly Property tag_averagecount() As Double
            Get
                Return tag_totalsum / Groove.admin_root.tags.Count
            End Get
        End Property

        Private ReadOnly Property tag_standeviation() As Double
            Get
                Dim sdsum As Integer = 0
                Dim t As Tag = Nothing
                For Each t In Groove.admin_root.tags
                    sdsum += Math.Pow((t.count - tag_averagecount), 2)
                Next
                Dim sdev As Double = Math.Sqrt(sdsum / Groove.admin_root.tags.Count)
                If sdev < Groove.admin_root.tags_min_occurance Then
                    Return Groove.admin_root.tags_min_occurance
                Else
                    Return sdev
                End If
            End Get
        End Property

        Private ReadOnly Property tag_totalsum() As Integer
            Get
                Dim sum As Integer = 0
                Dim t As Tag = Nothing
                For Each t In Groove.admin_root.tags
                    sum += t.count
                Next
                Return sum
            End Get
        End Property



        Private Const session_movers_key As String = "BOOGALOO_TAG_MOVERS"
#End Region
    End Class

End Namespace